package cn.wu.reggie.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.wu.reggie.common.R;
import cn.wu.reggie.entity.User;
import cn.wu.reggie.exception.BusinessException;
import cn.wu.reggie.mapper.UserMapper;
import cn.wu.reggie.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;


    @Override
    public R<User> login(String phone, String requestCode, String sessionCode) {
        // 1 判断用户输入的验证码是否为空
        if (StrUtil.isBlank(requestCode)) {
            throw new BusinessException("验证码不能为空");
        }
        // 2 判断session存在验证码
        if (StrUtil.isBlank(sessionCode)) {
            throw new BusinessException("请先获取验证码");
        }

        // 3 判断验证码是否一致 若不一致提示用户验证码错误
        if (!StrUtil.equals(requestCode,sessionCode)) {
            throw new BusinessException("验证码有误");
        }

        // 4 通过手机号查询是否有用户 若用户不存在新增 存在登录
        User user = userMapper.findByPhone(phone);
        if (user==null) {
            user = new User();
            user.setPhone(phone);
            user.setStatus(1);
            userMapper.save(user);
        }

        return R.success(user);
    }
}
